<!DOCTYPE html>
<html>

<head></head>
<!--计算属性和监听-->

<body>
    <div id="mainscreen" style="border:1px solid black">
        {{message}}
        <brook-cmp1 :parent="childElementBorderWidth">
        </brook-cmp1>
    </div>
</body>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<script type="text/javascript">
    // 组件可以嵌套
    // 上面就是一个例子
    var brookCmp2 = Vue.component("brook-cmp2", {
        props: ["child"],
        data: function () {
            return {
                text: "孙节点"
            };
        },
        computed: {
            style: function () {
                return "border:" + this.child + "px solid green"
            }
        },
        methods: {
            grandSonMethod: function (param) {
                // 可以直接调用vue实例的方法，这个是没问题的
                // vmInst.callMy001();
                // 但是不可以直接调用父类的方法，这样是不行的
                // brookCmp1.increaseBorderWidth()
                // 只能通过emit把事件抛出去，让父组件监听
                console.log("孙节点触发");
                this.$emit("increseparentborder", param);
            }
        },
        template: `<div :style=style><button @click="grandSonMethod(3)">{{text}}</button></div>`
    });

    var brookCmp1 = Vue.component("brook-cmp1", {
        props: ["parent"],
        data: function () {
            return {
                text: "子节点，点击触发父节点"
            };
        },
        // 计算属性，用于复杂生成场景
        computed: {
            style: function () {
                return 'border:' + this.parent + 'px solid orange';
            }
        },
        methods: {
            fireEventToRootNode: function () {
                console.log("子节点被点击，向根传递事件");
                vmInst.$emit("emitToRoot");
            },
            receiveEventFromGrandSonChild: function(){
                console.log("收到了来自孙子节点的事件");
            }
        },
        template: `<div :style=style><button @click="fireEventToRootNode">{{text}}</button><brook-cmp2 :child="parent" @increseparentborder="receiveEventFromGrandSonChild"></brook-cmp2></div>`
    });

    var vmInst = new Vue({
        data: {
            message: "父节点",
            labels: ["H101", "H201", "H301"],
            childElementBorderWidth: 2
        },
        methods: {
            callMy001: function () {
                console.log("callMy001");
            },
            callMy002: function () {
                console.log("事件被触发");
            }
        },
    });

    vmInst.$on('emitToRoot', function () {
        console.log("根节点收到了事件");
        this.childElementBorderWidth++;
    });
    vmInst.$mount("#mainscreen");
</script>

</html>